<template>
  <eui-background type="common">
    <eui-navbar ref="EuiNavBar" :title="title" :storeName="sUserStoreName" :storeId="sUserStore" displayable="true" />
    <view class="top-view">
      <eui-search-bar ref="RdsSearchBar" v-model="searchText" placeholder="请输入商品条码、编码" leftIcon="icon-saoyisao"
                      @confirm="searchConfirm" radius="30">
      </eui-search-bar>
    </view>
    <view class="footer-view" :style="{ height: listHeight + 'rpx' }">
      <scroll-view scroll-y="true" style="height: 100%;">
        <view style="display:flex;flex-direction: column">
          <eui-card title="基本信息" showTitleLine="true" h-padding="28">
            <template v-slot:extra>
              <view class="extra-view" @click="changeBasicStatus">
                <eui-uicons :type="showBasic ? 'up' : 'down'" size="24" />
              </view>
            </template>
            <view v-if="showBasic">
              <eui-card-input v-model="mainData.c_store_id" title="机构" placeholder="请选择机构" h-padding="0" alignType="left" :name="getName('rdsStores', mainData.c_store_id)"
                              type="textname2" required="true" @iconClick="clickRight('c_store_id')"
                              :rightIconType="(!(storeType === '2') || !(detailData.length > 0)) ? 'right' : ''"/>
              <eui-card-input v-model="mainData.c_adno" title="部门" placeholder="请选择部门" h-padding="0" alignType="left" :name="getName('rdsDeparts', mainData.c_adno)"
                              type="textname2" required="true" @iconClick="clickRight('c_adno')"
                              :rightIconType="mainData.c_status == '0' ? 'right' : ''"/>
              <eui-card-input v-model="mainData.c_chg_type" title="变价原因" :range="getUserDictSelectList('变价原因')" placeholder="请选择变价原因" h-padding="0" alignType="left"
                              type="selector" :displayable="mainData.c_status != '0'" :rightIconType="mainData.c_status == '0' ? 'right' : ''" @input="reqPrivOnInput" />
              <eui-card-input v-model="mainData.c_effect_da" title="生效日期" placeholder="请选择生效日期" h-padding="0" alignType="left" @input="effectDaChanged"
                              type="date" :displayable="mainData.c_status != '0'" :rightIconType="mainData.c_status == '0' ? 'right' : ''" />
              <eui-card-input v-model="mainData.c_affect_fields" :range="effectPropsItems" title="影响属性" placeholder="请选择影响属性" h-padding="0" alignType="left"
                              type="multi" :displayable="mainData.c_status != '0'" rightIconType="right" required="true" />
            </view>
          </eui-card>
          <eui-card hPadding="28" v-if="detailData && detailData.length > 0">
            <eui-swipe-action>
              <view :ref="'dataItem' + index" v-for="(item, index) in detailData" :key="index" @click="onClickGdsInfo(item, index)">
                <eui-swipe-actionitem :ref="`swipeActionItem${index}`" :right-options="options" show="none" :auto-close="true"
                                      @change="change" @click="bindClick($event, index)" :disabled="mainData.c_status != '0'">
                  <view class="item-view">
                    <eui-text type="name2" :value="index + 1 + '. ' + '[' + item.c_gcode + ']' + item.c_gname" cWidth="width: 100%" />
                    <eui-text type="name2" :value="item.c_barcode" title="主条码" />
                    <eui-text type="titlename2" :value="item.c_adno" :name="getRelatedName('rdsDeparts', item.c_adno)" title="部门"></eui-text>
                    <eui-text type="name2" :value="getRelatedName('rdsGdsclasses', item.c_ccode)" title="品类"></eui-text>
                    <eui-text type="slash2" :value="item.c_b_n" :name="item.c_unit" title="包装/单位"/>
                    <eui-text type="name2" :value="getDictName('价格敏感度', item.c_price_sens)" title="价格敏感度"></eui-text>
                    <eui-text type="name2" :value="getDictName('价格类型', item.c_is_barcode)" title="价格类型"></eui-text>
                    <eui-text type="price2" title="最低售价" :value="item.c_min_price" :valueStyle="showRightStyle"/>
                    <eui-text type="price2" title="建议售价" :value="item.c_advice_price" :valueStyle="showRightStyle"/>
                    <eui-text type="price2" title="售价" :value="item.c_price" :valueStyle="showRightStyle"/>
                    <eui-text type="price2" title="会员价" :value="item.c_price_mem" :valueStyle="showRightStyle"/>
                    <eui-text type="price2" title="批发价" :value="item.c_wprice" :valueStyle="showRightStyle"/>
                    <eui-text type="price2" title="采购毛利率(%)" :value="item.c_gross_profit" :valueStyle="showRightStyle"/>
                    <eui-text type="price2" title="成本毛利率(%)" :value="item.c_gross_profit_cost" :valueStyle="showRightStyle"/>
                    <eui-text type="price2" title="当前采购进价" :value="item.c_pt_in" :valueStyle="showRightStyle"/>
                    <eui-text type="price2" title="成本价" :value="item.c_pt_cost" :valueStyle="showRightStyle"/>
                    <eui-text type="price2" title="最后进价" :value="item.c_last_pt_in" :valueStyle="showRightStyle"/>
                  </view>
                  <view class="line-view" />
                </eui-swipe-actionitem>
              </view>
            </eui-swipe-action>
          </eui-card>
        </view>
      </scroll-view>
    </view>
    <view class="bottom-view">
      <view class="center-style">
        <eui-fab direction="vertical" :content='uniFabContent' @trigger="trigger"
                 v-if="mainData.c_id && mainData.c_status == '0' && detailData.length > 0">
        </eui-fab>
        <eui-button type="max2" title="保存" singleTag="保存" @buttonClick="confirm" :disabled="!(mainData.c_status == '0' && detailData.length > 0 && btnSaveEnabled)" />
        <eui-button type="max" title="审核" singleTag="审核" @buttonClick="confirm" :disabled="!(mainData.c_status == '0' && detailData.length > 0)" />
      </view>
    </view>
    <eui-popup ref="gdsPopup" background-color="#f8f8f8" type="bottom" :mask-click="false">
      <view class="popup-content">
        <view class="popup-title">编辑</view>
        <view style="padding-left: 10rpx;">
          <view class="item-view">
            <eui-text type="slash2" :value="currentGds.c_b_n" :name="currentGds.c_unit" title="包装/单位"/>
            <eui-text type="name2" :value="getDictName('价格敏感度', currentGds.c_price_sens)" title="价格敏感度"></eui-text>
            <eui-text type="name2" :value="getDictName('价格类型', currentGds.c_is_barcode)" title="价格类型"></eui-text>
            <eui-text type="price2" title="最低售价" :value="currentGds.c_min_price" :valueStyle="showRightStyle"/>
            <eui-text type="price2" title="建议售价" :value="currentGds.c_advice_price" :valueStyle="showRightStyle"/>
            <eui-text type="price2" title="售价" :value="currentGds.c_price" :valueStyle="showRightStyle"/>
            <eui-text type="price2" title="会员价" :value="currentGds.c_price_mem" :valueStyle="showRightStyle"/>
            <eui-text type="price2" title="批发价" :value="currentGds.c_wprice" :valueStyle="showRightStyle"/>
            <eui-text type="price2" title="采购毛利率(%)" :value="currentGds.c_gross_profit" :valueStyle="showRightStyle"/>
            <eui-text type="price2" title="成本毛利率(%)" :value="currentGds.c_gross_profit_cost" :valueStyle="showRightStyle"/>
            <eui-text type="price2" title="当前采购进价" :value="currentGds.c_pt_in" :valueStyle="showRightStyle"/>
            <eui-text type="price2" title="成本价" :value="currentGds.c_pt_cost" :valueStyle="showRightStyle"/>
            <eui-text type="price2" title="最后进价" :value="currentGds.c_last_pt_in" :valueStyle="showRightStyle"/>
          </view>
          <eui-card-input v-model="currentGds.c_min_price" title="最低售价" type="number" isBlur
                          ref="cardMinPriceInput" maxlength="9" alignType="left" :required="true" @confirm="validateDetail" placeholder="0"
                          fieldName="c_min_price"
                          v-show="mainData.c_affect_fields.split(',').includes('c_min_price')" />
          <eui-card-input v-model="currentGds.c_advice_price" title="建议售价" type="number" isBlur
                          ref="cardAdvicePriceInput" maxlength="9" alignType="left" :required="true" @confirm="validateDetail" placeholder="0"
                          fieldName="c_advice_price"
                          v-show="mainData.c_affect_fields.split(',').includes('c_advice_price')" />
          <eui-card-input v-model="currentGds.c_price" title="售价" type="number" isBlur
                          ref="cardPriceInput" maxlength="9" alignType="left" :required="true" @confirm="validateDetail" placeholder="0"
                          fieldName="c_price"
                          v-show="mainData.c_affect_fields.split(',').includes('c_price')" />
          <eui-card-input v-model="currentGds.c_price_mem" title="会员价" type="number" isBlur
                          ref="cardPriceMemInput" maxlength="9" alignType="left" :required="true" @confirm="validateDetail" placeholder="0"
                          fieldName="c_price_mem"
                          v-show="mainData.c_affect_fields.split(',').includes('c_price_mem')" />
          <eui-card-input v-model="currentGds.c_wprice" title="批发价" type="number" isBlur
                          ref="cardWpriceInput" maxlength="9" alignType="left" :required="true" @confirm="validateDetail" placeholder="0"
                          fieldName="c_wprice"
                          v-show="mainData.c_affect_fields.split(',').includes('c_wprice')" />
        </view>
        <view class="popup-bottom flex-1 flex">
          <eui-button type="max2" title="关闭" singleTag="关闭" @buttonClick="confirm"></eui-button>
          <eui-button type="max" title="确认" singleTag="确认" @buttonClick="confirm"></eui-button>
        </view>
      </view>
    </eui-popup>
    <eui-popup ref="popup" background-color="#f8f8f8" type="bottom" :mask-click="false">
      <view class="popup-content">
        <view class="popup-title">批量变价</view>
        <view style="padding-left: 5px;">
          <eui-card-input v-model="batchChangePrice.c_field" title="变更属性" type="radio"
                          @buttonClick="testFunc" :range="fieldItem" ref="fieldInput" alignType="left" />
          <eui-card-input v-model="batchChangePrice.c_basic_type" title="变更基数" type="radio"
                          :range="basicTypeItem"
                          :disabled="batchChangePrice.c_field == 'M'" ref="basicTypeInput" alignType="left" />
          <eui-card-input v-model="batchChangePrice.c_discount" title="折扣(%)" type="number"
                          @confirm="validateMain('c_discount', batchChangePrice.c_discount)"
                          ref="discountInput" alignType="left" maxlength="5" />
          <eui-card-input v-model="batchChangePrice.c_method" title="尾数处理方法" type="selector"
                          :range="methodList" alignType="left"
                          placement="top"/>
          <eui-card-input v-model="batchChangePrice.c_precision" title="精度" type="radio"
                          :range="precisionList" alignType="left" />
          <eui-card-input v-model="batchChangePrice.c_affect" title="作用域" type="radio"
                          :range="[{ text: '对所有行起作用', value: 'A' }]" alignType="left" />
        </view>
      </view>
      <view class="popup-bottom flex-1 flex">
        <eui-button type="max2" title="关闭" singleTag="关闭" @buttonClick="confirm"></eui-button>
        <eui-button type="max" title="确认" singleTag="确认2" @buttonClick="confirm"></eui-button>
      </view>
    </eui-popup>
    <eui-popup ref="popupMessage" background-color="#f8f8f8" type="center" :mask-click="false">
      <view class="popup-content-message">
        <view class="popup-title">提示</view>
        <scroll-view :scroll-top="0" scroll-y="true" class="list-scroll">
          <view v-for="(item, index) in modalInfos" :key="index">
            <eui-text :value="index + 1 + '. ' + item.c_gname" type="id" title="商品名称:" cWidth="width: 100%" />
            <eui-text :value="item.c_barcode" type="name2" title="条码:" cWidth="width: 100%" />
            <eui-text :value="item.c_message" type="name2" style="color:red" title="错误信息:" valueStyle="color: #FF4000;" cWidth="width: 100%" />
          </view>
        </scroll-view>
      </view>
      <view class="popup-bottom flex-1 flex" style="border-radius: 0 0 20rpx 20rpx">
        <eui-button type="max" title="关闭" singleTag="关闭" @buttonClick="confirm"></eui-button>
      </view>
    </eui-popup>
  </eui-background>
</template>

<script setup type="ts">
import {onMounted, ref, reactive} from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { validateGds, defaultMapping, validateStores } from '@/hooks/useValidateMethod';
import {formatNow, todayAdd} from '@/hooks/useUtils';
import service from "@/common/service";
import {getRdsUrl, rdsRequest} from '@/hooks/rdsServices';
import { calcAtInByPt, calculatePackages, round, validateProfitLimit, calcPriceByPrecision } from '@/hooks/useCalculateMethod';
import { useMainStore } from "@/store/modules/store";
import { useLoginStore } from "@/store/modules/useLoginStore";
import { getRelatedName, getDictName, getUserDictSelectList, getDictSelectList } from '../components/RelatedName.js';
import { getRdsUserDepartAuthority, getRdsSysConfig } from '@/hooks/init';
import dateRangUtil from "@/common/dateRangUtil";
import Enjoy from "@/common/enjoy";
import {validateAdnoLevel} from "@/hooks/useBillInfo";

const mainStore = useMainStore();
const LoginStore = useLoginStore();
const rdsUrl = getRdsUrl();
const RdsSearchBar = ref(null);
const gdsPopup = ref(null);
const popup = ref(null);
const popupMessage = ref(null);

const show = ref(false);
const isOpened = ref('none');
const isCurrentGds = ref([]);
const sUserStore = ref('');
const sUserStoreName = ref('');
const sUser = ref('');
const c_sku_rec = ref(0);
const c_n_rec = ref(0);
const title = ref('商品变价');
const c_id = ref('');//单据号
const c_gcode = ref('');
const searchText = ref('');
const height = ref(0);
const width = ref(0);
const storeType = ref('2');//[0]总部 [1]分区总部 [2]分店 [3]配送中心
const c_status = ref('0');
const detailData = ref([]);
const newList = ref([]);
const modifiedList = ref([]);
const delList = ref([]);
let currentGds = reactive({});
const currentGdsIndex = ref(0);
const methodList = ref([]);
const precisionList = ref([]);
const options = ref([{
  text: '删除',
  style: {
    backgroundColor: '#F56C6C',
  }
}]);
const uniFabContent = ref([
  {
    text: '删除单据'
  },
  {
    text: '批量变价'
  },
]);
const btnSaveEnabled = ref(true);
const showRightStyle = ref('text-align: right');
const effectPropsItems = ref([
  { text: '最低售价', value: 'c_min_price', checked: false },
  { text: '建议售价', value: 'c_advice_price', checked: false },
  { text: '售价', value: 'c_price', checked: true },
  { text: '会员价', value: 'c_price_mem', checked: true },
  { text: '批发价', value: 'c_wprice', checked: true }
]);
const sysConfig = ref({
  salePriceCanLessPromotion: '',//零售价是否可以小于促销价
});
const mainData = ref({
  c_tenant_id: '',
  c_id: '',
  c_bill_type: '081',
  c_status: '0',
  c_src_id: '',
  c_src_type: '',
  c_input_orig_mode: '1',
  c_store_id: sUserStore.value,
  c_store_name: sUserStoreName.value,
  c_value_mode: 'F',
  c_sample_code: sUserStore.value,
  c_sample_code_name: sUserStoreName.value,
  c_effect_da: todayAdd(1),
  c_adno: '',
  c_chg_type: getUserDictSelectList('变价原因')[0]?.value,
  c_apply_userno: sUser.value,
  // c_apply_username: username,
  c_buy_userno: '',
  c_charge_userno: '',
  c_org_no: '',
  c_affect_fields: 'c_price,c_price_mem,c_wprice',
  c_store_style: '',
  c_mk_type: '3',
  c_mk_store_id: sUserStore.value,
  c_mk_store_name: sUserStoreName.value,
  c_mk_dt: dateRangUtil.formatDate(new Date(),'YYYY-MM-DD HH:mm:ss'),
  c_mk_userno: sUser.value,
  c_approve_status: '1',
  c_au_userno: '',
  c_print_n: 0,
  c_print_userno: '',
  c_note: '',
  c_sys_note: '',
})
let batchChangePrice = reactive({
  c_field: 'P',
  c_basic_type: 'OP',
  c_discount: 100,
  c_method: '1',
  c_precision: 'f',
  c_affect: 'A'
})
const fieldItem = ref([]);//变更属性
const basicTypeItem = ref([]);//变更基数
const modalInfos = ref();//提示信息
const showBasic = ref(true);
const displayable = ref(false);  //true允许页面编辑
const listHeight = ref(300);

onLoad(async (option) => {
  sUserStore.value = option.storeId;
  if (option.storeId) {
    const result = await validateStores(
        { fieldName: 'c_store_id', row: mainData.value, newValue: option.storeId },
        { ischecklimit: true, firstValueMode: true }
    );
    storeType.value = result.c_type;
  }

  mainData.value.c_id = option.c_id;
  c_gcode.value = option.c_gcode;
  if (option.c_id) {
    title.value = option.c_id;
    await billQuery();
  }
  await setDefault();
  await getSysConfig();
})

onMounted(() => {
  getListHeight()
})

// 获取列表高度
const getListHeight = async () => {
  await uni.getSystemInfo({
    success: function (res) { // res - 各种参数
      let info = uni.createSelectorQuery().select(".footer-view");
      info.boundingClientRect(function (data) { //data - 各种参数
        //获取列表高度
        let height = res.windowHeight - data.top;
        //转换rpx
        let finalHeight = height / (res.windowWidth / 750) - 100;
        listHeight.value = finalHeight;
      }).exec()
    }
  });
};

// 获取单据详情信息
const billQuery = async () =>  {
  if (!mainData.value.c_id) {
    return;
  }
  service.enjoyShowLoading('正在加载...');
  const req = {
    BillId: mainData.value.c_id,
  };
  const result = await rdsRequest(rdsUrl.bcApi, '商品变价单', 'EnjoyBillQuery', req, '081');
  service.enjoyHideLoading();
  if (result.ds.length > 0) {
    mainData.value = result.ds[0];
    detailData.value = result.ds1;
    detailData.value.forEach(x => {
      x.rowType = 0;
    })
    effectPropsItems.value.forEach(item => {
      if (mainData.value.c_affect_fields.indexOf(item.value) > -1) {
        item.checked = true;
      } else {
        item.checked = false;
      }
    });

    c_sku_rec.value = detailData.value.reduce((pre, current) => pre + (current.c_n > 0 ?? 0), 0);
    c_n_rec.value = detailData.value.reduce((pre, current) => pre + (current.c_n ?? 0), 0);
  } else {
    uni.showToast({
      duration: 3500,
      icon: 'none',
      title: '未查询到数据',
      mask: true,
    });
  }

}

const setDefault = async () => {
  const { loginInfo } = mainStore;
  sUserStore.value = loginInfo.sUserStore;
  sUserStoreName.value = loginInfo.sUserStoreName;
  sUser.value = loginInfo.sUser;
  mainData.value.c_store_id = loginInfo.sUserStore;
  mainData.value.c_mk_store_id = loginInfo.sUserStore;
  mainData.value.c_mk_userno = loginInfo.sUser;
  methodList.value = getDictSelectList('价格尾数处理方法');
  precisionList.value = getDictSelectList('价格精度');
}

const getSysConfig = async () => {
  sysConfig.value.salePriceCanLessPromotion = await getRdsSysConfig("采购管理参数", "零售价是否可以小于促销价");
}

const changeBasicStatus = () => {
  showBasic.value = !showBasic.value;
}

const searchConfirm = async (e) => {
  if (!e) {
    return;
  }
  let searchValue = e.value;
  if (!mainData.value.c_adno) {
    uni.showToast({
      duration: 3500,
      icon: 'none',
      title: '请先选择部门！'
    });
    setTimeout(() => {
      clickRight('c_adno')
    }, 1000);
    return;
  }
  if (!mainData.value.c_affect_fields) {
    uni.showToast({
      duration: 3500,
      icon: 'none',
      title: '请勾选影响属性'
    });
    return;
  }
  searchText.value = searchValue;
  const itemIndex = detailData.value.findIndex(i => i.c_gcode == searchValue || i.c_barcode == searchValue);
  if (itemIndex !== -1) {
    const item = detailData.value[itemIndex];
    currentGds = item;
    if (mainData.value.c_status != '0') {
      return;
    }
    return true;
  } else {
    if (mainData.value.c_status != '0') {
      const itemIndex = detailData.value.findIndex(i => i.c_barcode === searchValue || i.c_gcode === searchValue);
      if (itemIndex !== -1) {
        const item = detailData.value[itemIndex];
        currentGds = item;
      } else {
        uni.showToast({
          duration: 2000,
          icon: 'none',
          title: '未查询到商品'
        });
      }
      return;
    }
    // TODO:如果缓存数据不存在，调用服务验证商品是否存在
    currentGds = initRow();
    let args = { fieldName: 'c_gcode', row: currentGds, newValue: searchText.value, };
    service.enjoyShowLoading('正在加载...');
    const result = await validateGds({
      url: rdsUrl.bcApi, uniqueKey: '商品变价单', billType: '081', args,
      head: {
        level: '1',
        code: mainData.value.c_store_id.split(','),
        adno: mainData.value.c_adno,
        value_mode: 'F',
        sample_code: '',
        login_store: sUserStore.value,
      },
      listManager: detailData.value,
      mapping: [
        ...defaultMapping,
        ['c_store_id', 'c_store_id'],
        ['c_price', 'c_price'],
        ['c_tax_rate', 'c_tax_rate'],
        ['c_gcode', 'c_gcode'],
        ['c_gname', 'c_name'],
        ['c_is_barcode', 'c_is_barcode'],
        ['c_b_n', 'c_n'],
        ['c_price', 'c_price'],
        ['c_price_old', 'c_price'],
        ['c_min_price', 'c_min_price'],
        ['c_min_price_old', 'c_min_price'],
        ['c_advice_price_old', 'c_advice_price'],
        ['c_advice_price', 'c_advice_price'],
        ['c_price_mem_old', 'c_price_mem'],
        ['c_price_mem', 'c_price_mem'],
        ['c_wprice_old', 'c_wprice'],
        ['c_wprice', 'c_wprice'],
        ['c_price_disc', 'c_price_disc'],
        ['c_pro_status', 'c_pro_status'],
        ['c_pt_cost', 'c_pt_cost'],
        ['c_pt_in', 'c_pt_in'],
        ['c_last_pt_in', 'c_last_pt_in'],
        ['c_model', 'c_model'],
        ['c_unit', 'c_unit'],
        ['c_price_sens', 'c_price_sens'],
        ['c_gross_profit', 'c_gross_profit'],
        ['c_gross_profit_old', 'c_gross_profit_old'],
        ['c_gross_profit_cost', 'c_gross_profit_cost'],
        ['c_gross_profit_cost_old', 'c_gross_profit_cost_old'],
        ['c_profit_limit_low', 'c_profit_limit_low'],
        ['c_profit_limit_top', 'c_profit_limit_top'],
      ],
      initRow: initRow,
      // currentRow:this.currentGds,
      callback: async (dataItems) => {
        if (dataItems?.length) {
          dataItems.filter(a => (!a.c_chk_msginfo)).map((item) => {
            // 录入商品编码时，不带出削价条码
            if (item.c_code === item.c_gcode && item.c_bar_type === '9') {
              dataItems.splice(dataItems.indexOf(item), 1);
            }
            const { c_is_primary_bar = '', c_ext1 } = item || {};
            item['c_is_barcode'] = c_is_primary_bar === 'Y' ? 'G' : 'B';

            // 如果是条码价格，则计算最低价和建议售价
            if (c_ext1 === 'B') {
              item['c_min_price'] = item['c_n'] * item['c_min_price'];
              item['c_advice_price'] = item['c_n'] * item['c_advice_price'];

            }
            if (item['c_pt_cost']) {
              item['c_pt_cost'] = item['c_n'] * item['c_pt_cost'];
            }
            if (item['c_pt_in']) {
              item['c_pt_in'] = item['c_n'] * item['c_pt_in'];
            }
            if (item['c_last_pt_in']) {
              item['c_last_pt_in'] = item['c_n'] * item['c_last_pt_in'];
            }

            //采购毛利率、成本毛利率 计算
            item['c_gross_profit'] = calcGrossProfit(item['c_price'], item['c_pt_in']);
            item['c_gross_profit_old'] = calcGrossProfit(item['c_price'], item['c_pt_in']);

            item['c_gross_profit_cost'] = calcGrossProfit(item['c_price'], item['c_pt_cost'] || item['c_pt_in']);
            item['c_gross_profit_cost_old'] = calcGrossProfit(item['c_price'], item['c_pt_cost'] || item['c_pt_in']);

          })
        }
        return true;
      }
    })
    service.enjoyHideLoading();
    setTimeout(() => {
      RdsSearchBar.value.clear();
    }, 300);
  }
}

// 保存数据
const saveBill = async (showToast) => {
  const flag = mainData.value.c_id;
  if (!flag) {
    const getBilllIdReq = {
      BillIdKeyValue: {
        key: "c_id",
        value: ""
      },
      BillVariable: "",
      TableName: "tb_mo_cgp",
      BillName: "商品变价单"
    }
    const billlId = await rdsRequest(rdsUrl.mainApi, '单号生成服务', 'EnjoyGetBillId', getBilllIdReq, '081');
    if (billlId) {
      mainData.value.c_id = billlId;
      title.value = billlId;
      mainData.value.c_mk_userno = sUser.value;
    }
  } else {
    mainData.value.c_modify_userno = sUser.value;
    mainData.value.c_modify_dt = dateRangUtil.formatDate(new Date(),'YYYY-MM-DD HH:mm:ss');
  }

  detailData.value.forEach(x => x.c_id = mainData.value.c_id)
  newList.value = detailData.value.filter(x => x.rowType == 1 || !x.hasOwnProperty('rowType'));
  modifiedList.value = detailData.value.filter(x => x.rowType == 2);
  const req = {
    NewList: flag ? [] : [mainData.value],
    ModifiedList: flag ? [mainData.value] : [],
    DelList: [],
    TableName: "tb_mo_cgp",
    PrimaryKeys: ["c_tenant_id", "c_id"],
    ChildData: [{
      ChildTableName: "tb_mo_cgp_g",
      ParentTableName: "tb_mo_cgp",
      ChildColumnNames: ["c_id"],
      ParentColumnNames: ["c_id"],
      ChildSaveModel: {
        NewList: newList.value,
        ModifiedList: modifiedList.value,
        DelList: delList.value,
        TableName: "tb_mo_cgp_g",
        PrimaryKeys: ["c_tenant_id", "c_id", "c_sort"],
      },
    }],
    BillSet: {
      BillIdKeyValue: {
        key: "c_id",
        value: mainData.value.c_id
      },
      BillVariable: "",
      TableName: "tb_mo_cgp",
      BillName: "商品变价单"
    },
  };
  const result = await rdsRequest(rdsUrl.bcApi, '商品变价单', 'EnjoyBillSaveNew', req, '081');
  if (showToast) {
    uni.showToast({
      duration: 3500,
      icon: 'none',
      title: `保存成功`
    });
  }
  newList.value = [];
  modifiedList.value = [];
  delList.value = [];
}

// 计算当前金额
const calcRowAmount = () => {
  currentGds.c_at_pay = calcAtInByPt({ c_pt: currentGds.c_pt_pay, c_n: currentGds.c_n });
  currentGds.c_at_in = calcAtInByPt({ c_pt: currentGds.c_pt_in, c_n: currentGds.c_n });
  currentGds.c_aet_pay = calcAtInByPt({ c_pt: currentGds.c_pet_pay, c_n: currentGds.c_n });
  currentGds.c_at_sale = calcAtInByPt({ c_pt: currentGds.c_price, c_n: currentGds.c_n });
  const itemIndex = detailData.value.findIndex(i => i.c_gcode == currentGds.c_gcode);
  if (itemIndex !== -1) {
    detailData.value[itemIndex] = currentGds; // 更新原数据
  }
  calcMainAmount();
}

const calcMainAmount = () => {
  mainData.value.c_at_sale = detailData.value.reduce((pre, current) => pre + current.c_at_sale, 0);
  mainData.value.c_at_req = detailData.value.reduce((pre, current) => pre + current.c_at_pay, 0);
  mainData.value.c_at_disc = detailData.value.reduce((pre, current) => pre + round((current.c_pt_pay_con - current.c_pt_pay) * current.c_n, 2), 0);
  //已录入品种数和已录入数量
  c_sku_rec.value = detailData.value.reduce((pre, current) => pre + (current.c_n > 0 ?? 0), 0);
  c_n_rec.value = detailData.value.reduce((pre, current) => pre + (current.c_n ?? 0), 0);
}

// 计算毛利率
const calcGrossProfit = (price, pt) => {
  if ((price ?? 0) === 0) {
    return 0;
  }
  return round((price - (pt ?? 0)) / price, 4) * 100;
}

const initRow = (index) => {
  const sort = Math.max(0, ...detailData.value.map(f => f.c_sort)) + 1 + index || 0;
  return {
    c_tenant_id: '',
    c_id: '',
    c_sort: sort,
    c_gcode: '',
    c_gname: '',
    c_store_id: '',
    c_store_name: sUserStoreName.value,
    // c_store_name_en: defaultStoreNameEn,
    c_barcode: '',
    c_is_barcode: 'G',
    c_price_sens: '',
    c_adno: '',
    c_ccode: '',
    c_unit: '',
    c_b_n: 1,
    c_min_price: 0,
    c_advice_price: 0,
    c_price_old: 0,
    c_price: 0,
    c_price_mem_old: 0,
    c_price_mem: 0,
    c_wprice_old: 0,
    c_wprice: 0,
    c_price_disc: 0,
    c_pro_status: '',
    c_pt_cost: 0,
    c_pt_in: 0,
    c_last_pt_in: 0,
    c_gross_profit: 0,
    c_gross_profit_old: 0,
    c_gross_profit_cost: 0,
    c_gross_profit_cost_old: 0,
    c_note: '',
    rowType: 1,
  }
}

const validateMain = async(t, e) => {
  const { loginInfo } = mainStore;
  switch (t) {
    case 'c_adno':
      if (!e) {
        uni.showToast({
          duration: 3500,
          icon: 'none',
          title: '部门不能为空'
        });
        // this.$refs.cardAdnoInput.getFocus();
        return;
      }
      const validateResult = await validateAdnoLevel({ IuputData: e, billKind: "08", tenantId: loginInfo.idsToken.tenantid });
      if (validateResult && validateResult.HasException) {
        uni.showToast({
          duration: 3500,
          icon: 'none',
          title: validateResult.Exception.Message
        });
        setTimeout(() => {
          clickRight('c_adno')
        }, 1000);
        return;
      }
      const lsGds = detailData.value.filter(i => i.c_gcode?.length > 0);
      if (lsGds.length > 0 && lsGds.some(i => i.c_adno.startsWith(e) == false)) {
        uni.showToast({
          duration: 3000,
          icon: 'none',
          title: '录入部门与明细商品部门不匹配！'
        });
        return;
      }
      break;
    case 'c_discount':
      if (!e) {
        batchChangePrice.c_discount = 100;
        return;
      }
      if (e < 0) {
        uni.showToast({
          duration: 3500,
          icon: 'none',
          title: '折扣不可小于0！'
        });
        setTimeout(() => {
          // this.$refs.discountInput.getFocus();
        }, 300);
        return;
      }
      break;
  }
}

const validateDetail = async (args) => {
  // service.enjoyShowLoading('正在加载...');
  const { type, fieldName, oldValue, newValue, itemIndex } = args;
  // this.currentGds = this.detailData[itemIndex];
  let warnMsg = '';
  switch (fieldName) {
    case 'c_min_price':
      currentGds.c_min_price = newValue;
      currentGds.c_err_msg = '';
      if (newValue === 0) {
        return;
      }
      if (newValue > currentGds.c_price) {
        warnMsg += `当前设置最低售价高于售价[${currentGds.c_price}]！`
      }
      if (newValue < currentGds.value.c_pt_in) {
        warnMsg += `当前设置最低售价低于进价[${currentGds.c_pt_in}]！`
      }
      break;
    case 'c_advice_price':
      currentGds.c_err_msg = ''
      if (newValue === 0) {
        return;
      }
      if (newValue < currentGds.c_pt_in) {
        warnMsg += `当前设置建议售价低于进价[${currentGds.c_pt_in}]！`
      }
      break;
    case 'c_price':
      currentGds.c_price = newValue;
      if (newValue === 0) {
        uni.showToast({
          duration: 3500,
          icon: 'none',
          title: '售价不可为0!'
        });
        setTimeout(() => {
          // this.$refs.cardPriceInput.getFocus()
        }, 300);
        return;
      }
      if ((newValue ?? 0) < (currentGds.c_price_mem ?? 0)) {
        uni.showToast({
          duration: 1000,
          icon: 'none',
          title: '售价不可低于会员价!',
          mask: true
        });
        setTimeout(() => {
          // this.$refs.cardPriceInput.getFocus();
        }, 300);
        return;
      }
      if (((newValue ?? 0) < (currentGds.c_price_disc ?? 0)) && !sysConfig.value.salePriceCanLessPromotion) {
        uni.showToast({
          duration: 1000,
          icon: 'none',
          title: '售价不可低于促销售价!'
        });
        setTimeout(() => {
          // this.$refs.cardPriceInput.getFocus()
        }, 300);
        return;
      }
      let currentProfit = calcGrossProfit(newValue, currentGds.c_pt_cost || currentGds.c_pt_in)
      const valResult = validateProfitLimit({
        currentProfit,
        profitLimitlow: currentGds.c_profit_limit_low,
        profitLimitTop: currentGds.c_profit_limit_top,
        gdsPriceSence: currentGds.c_price_sens
      })
      if (!valResult.validated) {
        uni.showToast({
          duration: 3500,
          icon: 'none',
          title: valResult.message
        });
        setTimeout(() => {
          // this.$refs.cardPriceInput.getFocus()
        }, 300);
        return;
      }
      currentGds.c_err_msg = '';
      if (valResult.message) {
        warnMsg += valResult.message
      }
      currentGds.c_gross_profit = calcGrossProfit(newValue, currentGds.c_pt_in)
      currentGds.c_gross_profit_cost = calcGrossProfit(newValue, currentGds.c_pt_cost || currentGds.c_pt_in);
      break;
    case 'c_price_mem':
      currentGds.c_price_mem = newValue;
      if (newValue === 0) {
        currentGds.c_err_msg = '';
        return;
      }
      if (newValue > currentGds.c_price) {
        uni.showToast({
          duration: 3500,
          icon: 'none',
          title: `当前设置会员价高于售价[${currentGds.c_price}]！`
        });
        setTimeout(() => {
          // this.$refs.cardPriceMemInput.getFocus();
        }, 300);
        return;
      }
      currentGds.c_err_msg = '';
      if (newValue < currentGds.c_pt_in) {
        warnMsg += `当前设置会员价低于进价[${currentGds.c_pt_in}]！`
      }
      break;
    case 'c_wprice':
      currentGds.c_wprice = newValue;
      currentGds.c_err_msg = '';
      if (newValue === 0) {
        return;
      }
      if (newValue > currentGds.c_price) {
        warnMsg += `当前设置的批发价高于售价[${currentGds.c_price}]！`;
      }
      if (newValue < currentGds.c_pt_in) {
        warnMsg += `当前设置的批发价低于进价[${currentGds.c_pt_in}]！`
      }
      break;
  }
  if (warnMsg) {
    uni.showToast({
      duration: 3500,
      icon: 'none',
      title: `${warnMsg}`
    });
  }

}

const trigger = (e) => {
  if (!mainData.value.c_id) {
    uni.showToast({
      duration: 3500,
      icon: 'none',
      title: '单据号不能为空！'
    });
    return false;
  }
  const { loginInfo } = mainStore;
  const req = {
    BillId: mainData.value.c_id,
    UserNo: loginInfo.sUser,
  }
  switch (e.item.text) {
    case '批量变价':
      fieldItem.value = [
        ...(mainData.value.c_affect_fields?.split(',').findIndex(a => a === 'c_price') >= 0 ? [{ value: 'P', text: '售价' }] : []),
        ...(mainData.value.c_affect_fields?.split(',').findIndex(a => a === 'c_price_mem') >= 0 ? [{ value: 'M', text: '会员价' }] : []),
        ...(mainData.value.c_affect_fields?.split(',').findIndex(a => a === 'c_wprice') >= 0 ? [{ value: 'W', text: '批发价' }] : []),
      ]

      batchChangePrice.c_field = mainData.value.c_affect_fields.split(',').includes('c_price') ? 'P' : mainData.value.c_affect_fields.split(',').includes('c_price_mem') ? 'M' : 'W';

      basicTypeItem.value = [
        { value: 'OP', text: '原售价' },
        ...(batchChangePrice.c_field === 'M' ? [{ value: 'OM', text: '原会员价' }] : []),
        ...(batchChangePrice.c_field === 'W' ? [{ value: 'OW', text: '原批发价' }] : [])
      ]

      popup.value.open('bottom')
      break;
    case '删除单据':
      if (mainData.value.c_status == "0") {
        uni.showModal({
          title: ' 提示',
          content: '请确认，删除单据[' + req.BillId + ']?',
          showCancel: true,
          success: async (res) => {
            if (res.confirm) {
              service.enjoyShowLoading('正在删除...');
              const result = await rdsRequest(rdsUrl.bcApi, '商品变价单', 'EnjoyBillDelete', req, '081');
              service.enjoyHideLoading();
              uni.showToast({
                duration: 3500,
                icon: 'none',
                title: '操作成功'
              });
              uni.redirectTo({
                url: './index'
              });
            }
          }
        });
      }
      break;
  }
}

const confirm = async (t) => {
  const { loginInfo } = mainStore;
  let { singleTag } = t;
  switch (singleTag) {
    case '保存':
      if (detailData.value.length <= 0) {
        uni.showToast({
          duration: 3500,
          icon: 'none',
          title: '请录入商品！'
        });
        setTimeout(() => {
          // this.$refs.RdsSearchBar.clearIcon();
        }, 300);
        return;
      }
      if (mainData.value.c_affect_fields.length <= 0) {
        uni.showToast({
          duration: 3500,
          icon: 'none',
          title: '至少选择一项影响属性！'
        });
        return;
      }
      btnSaveEnabled.value = false;
      // 保存
      service.enjoyShowLoading('正在保存...');
      await saveBill(true);
      await billQuery();
      service.enjoyHideLoading();
      setTimeout(() => {
        btnSaveEnabled.value = true;
      }, 100);
      break;
    case '审核':
      //审核
      if (detailData.value.length <= 0) {
        uni.showToast({
          duration: 3500,
          icon: 'none',
          title: '商品不能为空！'
        });
        return;
      }
      if (mainData.value.c_status == '0') {
        service.enjoyShowLoading();
        await saveBill(false);
        service.enjoyHideLoading();
        const req = {
          BillId: mainData.value.c_id,
          UserNo: loginInfo.sUser,
        }
        uni.showModal({
          title: ' 提示',
          content: '请确认，审核单据[' + req.BillId + ']?',
          showCancel: true,
          success: async (res) => {
            if (res.confirm) {
              service.enjoyShowLoading('正在审核...');
              const result = await rdsRequest(rdsUrl.bcApi, '商品变价单', 'EnjoyBillAudit', req, '081');
              service.enjoyHideLoading();
              uni.showToast({
                duration: 3500,
                icon: 'none',
                title: ' 审核成功！'
              });
              setTimeout(async () => {
                await billQuery();
              }, 300);
            } else if (res.cancel) {
              await billQuery();
            }
          }
        });
      }
      break;
    case '关闭':
      popup.value.close();
      gdsPopup.value.close();
      popupMessage.value.close();
      break;
    case '确认':
      service.enjoyShowLoading("正在加载...");
      currentGds.rowType = (currentGds.rowType === 1 || currentGds.rowType === undefined) ? 1 : 2;
      detailData.value[currentGdsIndex.value] = currentGds;
      gdsPopup.value.close();
      service.enjoyHideLoading();
      break;
    case '确认2':
      uni.showModal({
        title: ' 提示',
        content: '确定批量变价吗？',
        showCancel: true,
        success: async (res) => {
          if (res.confirm) {
            setTimeout(() => {
              popup.value.close();
            }, 300);

            service.enjoyShowLoading("正在加载...");
            // 清空所有的批量变价错误信息
            detailData.value.filter(a => a.c_err_msg).map(a => {
              a.c_err_msg = ''
            })

            // 受影响行
            // let rows = batchChangePrice.c_affect === 'A';
            let rows = detailData.value;

            //需要展示的错误或者提示信息
            modalInfos.value = [];

            if (batchChangePrice.c_field === 'M') {  // 会员价
              rows.map(a => {
                const newMemP = calcPriceByPrecision({
                  inputPrice: ((batchChangePrice.c_basic_type === 'OP' ? a.c_price_old : a.c_price_mem_old) * batchChangePrice.c_discount) / 100,
                  priceMethod: batchChangePrice.c_method,
                  pricePrecision: batchChangePrice.c_precision
                })
                a.c_err_msg = '';
                if (newMemP > a.c_price) {
                  modalInfos.value.push({
                    c_gcode: a.c_gcode,
                    c_gname: a.c_gname,
                    c_barcode: a.c_barcode,
                    c_type: '0',
                    c_message: `当前设置的会员价[${newMemP}]高于售价${a.c_price}!`
                  });
                  a.c_err_msg = `批量变价错误：设置的会员价[${newMemP}]高于售价${a.c_price}!`
                } else {
                  if (newMemP < a.c_pt_in) {
                    // this.modalInfos.push({
                    // 	c_gcode: a.c_gcode,
                    // 	c_gname: a.c_gname,
                    // 	c_barcode: a.c_barcode,
                    // 	c_type: '2',
                    // 	c_message: `当前设置的会员价[${newMemP}]低于进价${a.c_pt_in}!`
                    // });
                    a.c_err_msg = `警告：当前会员价[${newMemP}]低于进价${a.c_pt_in}!`
                  }
                  a.c_price_mem = newMemP;
                }
              })
              if (modalInfos.value.length > 0) {
                popupMessage.value.open('center')
              } else {
                uni.showToast({
                  duration: 3500,
                  icon: 'none',
                  title: '修改成功！'
                });
                popup.value.close()
              }
            } else if (batchChangePrice.c_field === 'P') { // 售价
              rows.map(a => {
                a.c_err_msg = '';
                // 计算新价格
                const newPrice = calcPriceByPrecision({
                  inputPrice: (a.c_price_old * batchChangePrice.c_discount) / 100,
                  priceMethod: batchChangePrice.c_method,
                  pricePrecision: batchChangePrice.c_precision
                });
                if (newPrice === 0) {
                  modalInfos.value.push({
                    c_gcode: a.c_gcode,
                    c_gname: a.c_gname,
                    c_barcode: a.c_barcode,
                    c_type: '0',
                    c_message: `售价不可为0!`
                  });
                  a.c_err_msg = `批量变价错误：售价不可为0!`


                }
                else if (newPrice < (a.c_price_mem ?? 0)) {
                  modalInfos.value.push({
                    c_gcode: a.c_gcode,
                    c_gname: a.c_gname,
                    c_barcode: a.c_barcode,
                    c_type: '0',
                    c_message: `售价${newPrice}不可低于会员价${a.c_price_mem}!`
                  });
                  a.c_err_msg = `批量变价错误：售价[${newPrice}]低于会员价${a.c_price_mem}!`
                }
                //新售价是否低于促销价
                else if (((newPrice ?? 0) < (a.c_price_disc ?? 0)) && !sysConfig.value.salePriceCanLessPromotion) {
                  modalInfos.value.push({
                    c_gcode: a.c_gcode,
                    c_gname: a.c_gname,
                    c_barcode: a.c_barcode,
                    c_type: '0',
                    c_message: `售价${newPrice}不可低于促销售价${a.c_price_disc}!`
                  });
                  a.c_err_msg = `批量变价错误：售价[${newPrice}]低于促销售价${a.c_price_disc}!`

                } else { //计算成本毛利率是否符合
                  let currentProfit = calcGrossProfit(newPrice, a.c_pt_cost || a.c_pt_in);
                  const valResult = validateProfitLimit({
                    currentProfit,
                    profitLimitlow: a.c_profit_limit_low,
                    profitLimitTop: a.c_profit_limit_top,
                    gdsPriceSence: a.c_price_sens
                  })
                  if (valResult.message) {
                    modalInfos.value.push({
                      c_gcode: a.c_gcode,
                      c_gname: a.c_gname,
                      c_barcode: a.c_barcode,
                      c_type: valResult.validated ? '2' : '0',
                      c_message: valResult.message
                    });
                    a.c_err_msg = `${valResult.validated ? '警告：' : '批量变价错误：'}${valResult.message}!`

                  }
                  if (valResult.validated) {
                    a.c_price = newPrice;
                    a.c_gross_profit = calcGrossProfit(newPrice, a.c_pt_in);
                    a.c_gross_profit_cost = calcGrossProfit(newPrice, a.c_pt_cost || a.c_pt_in); //currentProfit;
                  }
                }

              })
              if (modalInfos.value.length > 0) {
                popupMessage.value.open('center')
              } else {
                uni.showToast({
                  duration: 3500,
                  icon: 'none',
                  title: '修改成功！'
                });
                popup.value.close()
              }
            } else { // 批发价
              rows.map(a => {
                a.c_err_msg = '';
                const newWP = calcPriceByPrecision({
                  inputPrice: ((batchChangePrice.c_basic_type === 'OP' ? a.c_price_old : a.c_wprice_old) * batchChangePrice.c_discount) / 100,
                  priceMethod: batchChangePrice.c_method,
                  pricePrecision: batchChangePrice.c_precision
                })
                if (newWP > a.c_price) {
                  modalInfos.value.push({
                    c_gcode: a.c_gcode,
                    c_gname: a.c_gname,
                    c_barcode: a.c_barcode,
                    c_type: '2',
                    c_message: `当前设置的批发价[${newWP}]高于售价[${a.c_price}]!`
                  });
                  a.c_err_msg = `警告：当前商品批发价[${newWP}]高于售价[${a.c_price}]!`
                }
                if (newWP < a.c_pt_in) {
                  // this.modalInfos.push({
                  // 	c_gcode: a.c_gcode,
                  // 	c_gname: a.c_gname,
                  // 	c_barcode: a.c_barcode,
                  // 	c_type: '2',
                  // 	c_message: `当前设置的批发价[${newWP}]低于进价[${a.c_pt_in}]!`
                  // });
                  a.c_err_msg = `警告：当前商品批发价[${newWP}]低于进价[${a.c_pt_in}]!`

                }
                a.c_wprice = newWP;
              })
              if (modalInfos.value.length > 0) {
                popupMessage.value.open('center')
              } else {
                uni.showToast({
                  duration: 3500,
                  icon: 'none',
                  title: '修改成功！'
                });
                popup.value.close()
              }
            }
            // if (!c_err_msg) {
            // 	uni.showToast({
            // 		duration: 3500,
            // 		icon: 'none',
            // 		title: `${c_err_msg}`
            // 	});
            // }
            if (modalInfos.value.length > 0) {
              //排除失败列表以及新增的数据
              detailData.value.forEach(x => {
                const isMatch = modalInfos.value.some(y => y.c_gcode === x.c_gcode || x.rowType == 1);
                if (!isMatch) {
                  x.rowType = 2;
                }
              });
            } else {
              detailData.value.forEach(x => {
                if (x.rowType != 1) {
                  x.rowType = 2;
                }
              });
            }
            service.enjoyHideLoading();
          }
        }
      });
      break;
  }
}

const onClickGdsInfo = (item, index) => {
  if (mainData.value.c_status != '0') {
    return;
  }
  if (mainData.value.c_affect_fields.length <= 0) {
    uni.showToast({
      duration: 3500,
      icon: 'none',
      title: '至少选择一项影响属性！'
    });
    return;
  }
  currentGdsIndex.value = index;
  currentGds = JSON.parse(JSON.stringify(item));
  gdsPopup.value.open('bottom');
}

const change = (e) => {
  isOpened.value = e;
}

// 变更属性
const fieldInput = (value) => {
  batchChangePrice.c_field = value;
  if (value == 'P') {
    basicTypeItem.value = [{ value: 'OP', text: '原售价', checked: true }]
    batchChangePrice.c_basic_type = 'OP';
  } else {
    basicTypeItem.value = [
      { value: 'OP', text: '原售价' },
      ...(batchChangePrice.c_field === 'M' ? [{ value: 'OM', text: '原会员价' }] : []),
      ...(batchChangePrice.c_field === 'W' ? [{ value: 'OW', text: '原批发价' }] : [])
    ]
  }
}

// 变更属性
const testFunc = (value) => {
  batchChangePrice.c_field = value;
  if (value == 'P') {
    basicTypeItem.value = [{ value: 'OP', text: '原售价', checked: true }]
    batchChangePrice.c_basic_type = 'OP';
  } else {
    basicTypeItem.value = [
      { value: 'OP', text: '原售价' },
      ...(batchChangePrice.c_field === 'M' ? [{ value: 'OM', text: '原会员价' }] : []),
      ...(batchChangePrice.c_field === 'W' ? [{ value: 'OW', text: '原批发价' }] : [])
    ]
  }
}

// 变价原因
const reqPrivOnInput = (value) => {
  mainData.value.c_chg_type = value
}

const basicTypeInput = (value) => {

}

const discountInput = (value) => {
  if (value < 0) {
    uni.showToast({
      duration: 3500,
      icon: 'none',
      title: '折扣不可小于0!'
    });
    return;
  }
}

// 校验生效日期
const effectDaChanged = (value) => {
  let nowDate = formatNow('YYYY-MM-DD');
  if (value < nowDate) {
    uni.showToast({
      duration: 3500,
      icon: 'none',
      title: '生效日期不可早于今天,请检查！'
    })
    setTimeout(() => {
      mainData.value.c_effect_da = nowDate;
    },200)
    return;
  }
}

const bindClick = (e, index) => {
  uni.showModal({
    title: ' 提示',
    content: '您确定要删除数据吗？',
    showCancel: true,
    success: async (res) => {
      if (res.confirm) {
        delList.value.push(detailData.value[index]);
        detailData.value.splice(index, 1);
      }
    }
  });
}

const getName = (key, value) => {
  if (!value) {
    return ''
  }
  let list = [];
  value.split(',').map(item => {
    list.push("[" + item + "]" + (getRelatedName(key, item) || key));
  })
  return list.join(',');
}

// 选择框点击事件
const clickRight = (type) => {
  let parms = Enjoy.GetDialogParms();
  parms.CallBack = SelectionChanged;
  if (type=='c_store_id') {
    parms.SelectionType = "机构选择";
    parms.SelectedItems = mainData.value.c_store_id;
  } else if (type=='c_adno') {
    parms.SelectionType = "部门选择";
    parms.SelectedItems = mainData.value.c_adno;
  }
  Enjoy.OpenDialog(parms)
}

const SelectionChanged = async (e) =>{
  const { loginInfo } = mainStore;
  if (e.SelectionType=='机构选择') {
    let curStoreId = e.BackParms.Key;
    if (curStoreId.split(',').length == 1) {
      const result = await validateStores(
          { fieldName: 'c_store_id', row: mainData.value, newValue: curStoreId },
          { ischecklimit: true, firstValueMode: true }
      );
      storeType.value = result.c_type;
      sUserStoreName.value = e.BackParms.Value;
      sUserStore.value = curStoreId;
      mainData.value.c_mk_store_id = sUserStore.value;
      if (result.c_type === '2') {
        mainData.value.c_store_id = curStoreId;
      }
    } else {
      mainData.value.c_store_id = curStoreId;
    }
  } else if (e.SelectionType=='部门选择') {
    //验证部门层级
    let curAdno = e.BackParms.Key;
    const validateResult = await validateAdnoLevel({ IuputData: curAdno, billKind: "08", tenantId: loginInfo.idsToken.tenantid });
    if (validateResult.HasException) {
      uni.showToast({
        duration: 3500,
        icon: 'none',
        title: validateResult.Exception.Message
      });
      setTimeout(() => {
        clickRight('c_adno')
      }, 1000);
      return;
    }
    const userAdno = await getRdsUserDepartAuthority(sUser.value);
    if (userAdno.includes(curAdno)) {
      mainData.value.c_adno = curAdno;
    } else {
      uni.showToast({
        duration: 3500,
        icon: 'none',
        title: `没有部门${curAdno}权限！`
      });
      setTimeout(() => {
        clickRight('c_adno')
      }, 1000);
      return
    }
    const lsGds = detailData.value.filter(i => i.c_gcode?.length > 0);
    if (lsGds.length > 0 && lsGds.some(i => i.c_adno.startsWith(curAdno) == false)) {
      uni.showToast({
        duration: 3500,
        icon: 'none',
        title: '录入部门与明细商品部门不匹配！'
      });
      setTimeout(() => {
        // this.$refs.cardAdnoInput.getFocus();
      }, 300);
      return;
    }
  }
}


</script>

<style lang="scss" scoped>
@import '../../../main.scss';
.top-view {
  width: 100%;
  height: 88rpx;
}
.extra-view {
  margin-right: 30rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 60rpx;
  height: 100%;
}
.footer-view {
  width: 100%;
  flex: 1;
}
.list-scroll {
  width: 100%;
  height: 300rpx;
  box-sizing: border-box;
}
.bottom-view {
  width: 100%;
  height: 100rpx;
  background: #FFFFFF;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  flex-direction: row;
}
.center-style {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  margin-right: 20rpx;
  gap: 20rpx;
}
//内容行
.item-view {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: center;
  margin-top: 16rpx;
  row-gap: 8rpx;
}
.line-view {
  width: 100%;
  height: 1rpx;
  background: #EEEEEE;
  margin: 20rpx 0;
}
.fab-view {
  width: 60rpx;
  height: 100%;
  //background: #00aaff;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}
.popup-content {
  align-items: center;
  justify-content: left;
  flex-direction: column;
  padding: 0;
  width: 100%;
  background-color: #ffffff;
}
.popup-content-message {
  align-items: center;
  justify-content: left;
  flex-direction: column;
  padding: 0 20rpx 20rpx 20rpx;
  width: 600rpx;
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
}
.popup-title {
  width: 100%;
  height: 84rpx;
  background: #FFFFFF;
  border-radius: 40rpx 40rpx 0 0;
  display: flex;
  justify-content: center;
  align-items: center;
  color: $uni-text-color-secondary;
  font-size: $uni-font-size-level1;
  line-height: 45rpx;
  text-align: center;
  position: relative;
}
.m-list-top {
  display: grid;
  grid-template-columns: 52% 48%;
  padding: 0 0 16rpx;
  border-bottom: 2px solid #c8c7cc;
  font-size: 24rpx;
}
.popup-bottom {
  background: #ffffff;
  border-top: 1rpx solid $uni-line-color;
  display: flex;
  justify-content: center;
  padding: 20rpx;
}
</style>
